#coding=utf8
from . import publisher

from flask import render_template, redirect, url_for, flash, session, request
from forms import PublisherRegisterForm, LoginForm, ActivityForm
from ..models import Publisher, Activity
from werkzeug.security import generate_password_hash
from werkzeug import secure_filename
from datetime import datetime
from functools import wraps
from .. import db
from .. import app

import os
import uuid

# 内容发布者登录装饰器
def user_login_req(f):
	@wraps(f)
	def login_req(*args, **kwargs):
		if 'person_num' not in session:
			return redirect(url_for('publisher.login', next=request.url))
		return f(*args, **kwargs)
	return login_req

# 登录
@publisher.route('/login', methods=['GET', 'POST'])
def login():
	form = LoginForm()
	if form.validate_on_submit():
		data = form.data
		session['person_num'] = data['person_num']
		# print data['person_num']
		return redirect(url_for('publisher.add_activity'))
	return render_template('publisher/login.html', title=u'登录', form=form)


# 注册
@publisher.route('/register', methods=['GET', 'POST'])
def register():
	form = PublisherRegisterForm()
	if form.validate_on_submit():
		data = form.data
		publisher = Publisher(
			organization_name = data['organization_name'],
			official_accounts_name = data['official_accounts_name'],
			person_name = data['person_name'],
			person_num = data['person_num'],
			person_wechat_id = data['person_wechat_id'],
			phone_num = data['phone_num'],
			password = generate_password_hash(data['password']),
			register_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
		)
		# print publisher
		db.session.add(publisher)
		db.session.commit()
		flash(u'注册成功，请登录', 'ok')
		return redirect(url_for('publisher.login'))
	# else:
	# 	flash(u'注册失败，请重新注册', 'err')
	return render_template('publisher/register.html', title=u'注册', form = form)


# 退出 （302 重定向到登录页面）
@publisher.route('/logout', methods=['GET'])
@user_login_req
def logout():
	session.pop('person_num', None)
	return redirect(url_for('publisher.login'))


def change_filename(filename, time, file_uuid):
	info = os.path.splitext(filename)
	new_file_name = time.strftime("%Y%m%d%H%M%S")+'_'+file_uuid+info[-1]
	return new_file_name

# 活动发布
@publisher.route('/activity/add', methods=['GET', 'POST'])
@user_login_req
def add_activity():
	form = ActivityForm()
	if form.validate_on_submit():
		data = form.data
		# 获取logo
		filename = secure_filename(form.logo.data.filename)
		file_uuid = str(uuid.uuid4().hex)
		time_now = datetime.now()
		logo = change_filename(filename, time_now, file_uuid)
		form.logo.data.save(app.config['UP']+'/'+logo)

		publisher = Publisher.query.filter_by(person_num=session['person_num']).first()
		publisher_num = publisher.person_num

		activity = Activity(
			id = file_uuid,
			publisher_num = publisher_num,
			title = data['title'],
			adding_time = time_now.strftime("%Y-%m-%d %H:%M:%S"),
			closing_date = data['closing_date'],
			description = data['description'],
			new_activity_class = int(data['activity_class']),
			logo = logo,
			article_url = data['article_url'],
			remark = data['remark'],
			new_state = 0,
			count = 0,
			organization_name = publisher.organization_name
		)
		db.session.add(activity)
		db.session.commit()
		flash(u'活动已经提交给运维人员，请稍后再次登录该网址查询活动状态。', 'ok')
		# print data['closing_date']
		# print data['description']
	return render_template('publisher/add_activity.html', title=u'发布活动', form=form)

# 获取活动列表
@publisher.route('/activity/list/<int:page>', methods=['GET'])
@user_login_req
def activity_list(page=None):
	if page == None:
		page = 1
	page_data = Activity.query.filter_by(
		publisher_num=session['person_num']
	).order_by(
		Activity.adding_time.desc()
	).paginate(page=page, per_page=8)
	return render_template('publisher/activity_list.html', title=u'活动列表', page_data=page_data)

# 查看活动详情
@publisher.route('/activity/<activity_id>', methods=["GET"])
@user_login_req
def activity_detail(activity_id):
	activity = Activity.query.filter_by(
		id = activity_id
	).first()
	# print request.url
	return render_template('publisher/activity_detail.html', activity=activity)


# 基本信息
@publisher.route('/info', methods=['GET'])
@user_login_req
def basic_information():
	publisher = Publisher.query.filter_by(person_num=session['person_num']).first()
	organization_name = publisher.organization_name
	# print organization_name
	official_accounts_name = publisher.official_accounts_name
	person_name = publisher.person_name
	person_num = publisher.person_num
	# print person_num
	person_wechat_id = publisher.person_wechat_id
	phone_num = publisher.phone_num
	# print phone_num
	return render_template('publisher/info.html', title=u'基本信息',
	                       organization_name=unicode(organization_name),
	                       official_accounts_name=official_accounts_name,
	                       person_name=person_name,
	                       person_num=person_num,
	                       person_wechat_id=person_wechat_id,
	                       phone_num=phone_num)